package univ.lille1.fr.car;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateful;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import univ.lille1.fr.car.ejb.Auteur;
import univ.lille1.fr.car.ejb.Panier;
import univ.lille1.fr.car.manager.AuteurManager;

@Stateful
public class Connexion extends HttpServlet {

	private static final long serialVersionUID = 3226537737492672606L;
	AuteurManager auteurManager = new AuteurManager();
	HttpSession session;
	List<Auteur> listeAuteurs = new ArrayList<Auteur>();

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.getServletContext().getRequestDispatcher("/WEB-INF/connexion.jsp")
				.forward(request, response);

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String pseudo = request.getParameter("nom");
		String mdp = request.getParameter("password");
		boolean isOk = false;
		String message = "";

		try {
			if (pseudo.equals("toto") && mdp.equals("toto")) {

				// on start la session
				session = request.getSession(true);
				session.setAttribute("panier", new Panier());
				session.setAttribute("username", "toto");

				isOk = true;
				message = "Connexion reussi";
			} else {
				isOk = false;
				message = "Pseudo ou mpd incorrect";
			}
		} catch (Exception e) {
		}
		
		// initialisation de la DB
		this.listeAuteurs = Init.initDBAuteur(listeAuteurs, auteurManager);
		request.setAttribute("listeAuteurs", listeAuteurs);

		session.setAttribute("isOk", isOk);
		request.setAttribute("message", message);
		request.setAttribute("isOk", isOk);

		if (isOk) {
			this.getServletContext().getRequestDispatcher("/WEB-INF/init.jsp")
					.forward(request, response);
		} else {
			this.getServletContext()
					.getRequestDispatcher("/WEB-INF/connexion.jsp")
					.forward(request, response);
		}
	}
}
